package com.gin.no_gay_alliance.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.method.NukeApi;
import com.gin.nga.params.nuke.pm.PmNewParam;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.MsgCallback;
import com.gin.no_gay_alliance.databinding.ActivityPriMsgBinding;
import com.gin.no_gay_alliance.databinding.DialogPriMsgNewBinding;
import com.gin.no_gay_alliance.fragment.primsg.PriMsgBlockFragment;
import com.gin.no_gay_alliance.fragment.primsg.PriMsgListFragment;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.InputMethodManagerUtils;
import com.gin.no_gay_alliance.utils.MyHandler;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.io.Serializable;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 私信活动
 */
public class PriMsgActivity extends BaseBindingActivity<ActivityPriMsgBinding> implements TabLayoutMediator.TabConfigurationStrategy {
    public static final String TAG = PriMsgActivity.class.getSimpleName();
    TabLayoutMediator tabLayoutMediator;

    @Override
    protected void handleIntent(Intent intent) {

    }

    @Override
    protected void onCreate() {

        b.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                switch (position) {
                    case 0:
                        return new PriMsgListFragment();
                    case 1:
                        return new PriMsgBlockFragment();
                    default:
                        throw new IllegalStateException("Unexpected value: " + position);
                }
            }

            @Override
            public int getItemCount() {
                return 2;
            }
        });

        tabLayoutMediator = attachTabLayout(tabLayoutMediator, b.tabLayout, b.vp2);
    }


    @Override
    protected void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
        menuInflater.inflate(R.menu.pri_msg_menu, menu);
        // 隐藏离开按钮
        MenuItem item = menu.findItem(R.id.menu_item_pri_msg_quit);
        if (item != null) {
            item.setVisible(false);
        }
    }

    /**
     * 配置tabLayout的标签
     */
    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        switch (position) {
            case 0:
                tab.setText(R.string.private_message);
                break;
            case 1:
                tab.setText(R.string.black_list);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + position);
        }
    }

    @Override
    protected Toolbar initToolbar() {
        return b.toolbar;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // 发起私信
        if (item.getItemId() == R.id.menu_item_pri_msg_reply) {
            createPriMsg(this, handler);
        }
        return super.onOptionsItemSelected(item);
    }

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, PriMsgActivity.class));
    }

    /**
     * 弹窗，发起私信
     */
    public static void createPriMsg(Context context, MyHandler handler, Serializable... user) {
        DialogPriMsgNewBinding bb = DialogPriMsgNewBinding.inflate(LayoutInflater.from(context));

        // 如果传入了user
        if (!ObjectUtils.isEmpty(user)) {
            bb.etUser.setText(Arrays.stream(user).map(Object::toString).collect(Collectors.joining(",")));
        }
        String message = context.getString(R.string.tips_pri_msg_new);


        AlertDialog alertDialog = AlertDialogUtils.showConfirm(context, "发起私信", message, bb.getRoot(), (dialog, which) -> {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                String title = bb.etTitle.getText().toString();
                String content = bb.etContent.getText().toString();
                String userString = bb.etUser.getText().toString();
                Serializable[] split = userString.split(",");
                PmNewParam param = new PmNewParam(title, content, split);
                NukeApi.pmNew(MyApplication.getClient(), param).async(new MsgCallback(handler));
            }
        });

        alertDialog.setCanceledOnTouchOutside(false);

        // 表单校验
        Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        button.setEnabled(false);
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 发送回复
                String title = bb.etTitle.getText().toString();
                String content = bb.etContent.getText().toString();
                String userString = bb.etUser.getText().toString();
                button.setEnabled(!ObjectUtils.isEmpty(content) && !ObjectUtils.isEmpty(title) && !ObjectUtils.isEmpty(userString));
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };
        bb.etTitle.addTextChangedListener(watcher);
        bb.etContent.addTextChangedListener(watcher);
        bb.etUser.addTextChangedListener(watcher);


        EditText et = bb.etUser.getText().length() == 0 ? bb.etUser : bb.etTitle;
        et.requestFocus();
        InputMethodManagerUtils.show(handler, et);
    }
}